package com.inspector.app.ui.chat.adapter;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.inspector.app.databinding.ItemMenuBinding;
import com.inspector.app.ui.chat.entity.MenuEntity;

import java.util.ArrayList;
import java.util.List;

public class MenuAdapter extends RecyclerView.Adapter<MenuAdapter.ViewHolder> {
    private OnItemClickListener mOnItemClickListener;
    private ArrayList<MenuEntity> mList = new ArrayList<>();

    public void setOnItemClickListener(OnItemClickListener listener) {
        this.mOnItemClickListener = listener;
    }

    public void setData(List<MenuEntity> dataList) {
        this.mList.clear();
        this.mList.addAll(dataList);
        notifyDataSetChanged();
    }

    @NonNull
    @Override
    public MenuAdapter.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        ItemMenuBinding inflate = ItemMenuBinding.inflate(LayoutInflater.from(parent.getContext()), parent, false);
        return new ViewHolder(inflate, mOnItemClickListener);
    }

    @Override
    public void onBindViewHolder(@NonNull MenuAdapter.ViewHolder holder, int position) {
        MenuEntity menuEntity = mList.get(position);


        holder.binding.executePendingBindings();

        holder.bind(menuEntity, position);
    }

    @Override
    public int getItemCount() {
        return mList == null ? 0 : mList.size();
    }

    public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
        private ItemMenuBinding binding;
        private OnItemClickListener listener;

        public ViewHolder(@NonNull ItemMenuBinding binding, OnItemClickListener listener) {
            super(binding.getRoot());
            this.listener = listener;
            this.binding = binding;
            binding.getRoot().setOnClickListener(this);
        }

        public void bind(MenuEntity menuEntity, int position) {
            binding.name.setText(menuEntity.getName());
            binding.icon.setImageResource(menuEntity.getIcon());
        }

        @Override
        public void onClick(View view) {
            if (listener != null) {
                listener.onItemClick(view, getBindingAdapterPosition());
            }
        }
    }


    public interface OnItemClickListener {
        void onItemClick(View view, int position);
    }

}
